package com.zzm.common.shiro.realm;

import com.zzm.common.shiro.utils.ShiroUtil;
import com.zzm.common.utils.Md5Utils;
import com.zzm.system.menu.service.MenuService;
import com.zzm.system.role.entity.Role;
import com.zzm.system.role.service.RoleService;
import com.zzm.system.user.entity.User;
import com.zzm.system.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserReam extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Long userId = ShiroUtil.getUserId();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleService.selectRoles(userId));
        info.setStringPermissions(menuService.selectPermsByUserId(userId));
        return info;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();

        User userByusername = userService.selectUserByLoginName(username);
        User user = null;
        String password = "";
        if(token.getPassword() != null && !token.getPassword().equals("")){
            password = new String(token.getPassword());
        }

        String enPassword = Md5Utils.encript(username,password,Integer.parseInt(userByusername.getSalt()));
        try {
             user = userService.selectUserByLoginNameAndPassword(username,enPassword);
        } catch (Exception e) {
            throw new NullPointerException();
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,password,getName());
        return info;
    }
}
